﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JHSoft.Util
{
    public static class ModuleUtil
    {
        /// <summary>
        /// 将数据库查询的T转换为WCF返回的实体TModel
        /// </summary>
        /// <typeparam name="T">源类型</typeparam>
        /// <typeparam name="TModel">目标类型</typeparam>
        /// <param name="t">t表示要转的对象实例</param>
        /// <returns></returns>
        public static TModel ParseDomainToModel<T, TModel>(this T t)
            where T : class, new()
            where TModel : class, new()
        {
            var tType = t.GetType();
            var properties = tType.GetProperties();

            var tModel = new TModel();
            var tModelType = tModel.GetType();

            foreach (var property in properties)
            {
                var value = property.GetValue(t, null);
                var destProperty = tModelType.GetProperty(property.Name);
                if (destProperty != null)
                    destProperty.SetValue(tModel, value, null);
            }
            return tModel;
        }

        /// <summary>
        /// 将数据库查询的List T转换为WCF返回的实体List TModel
        /// </summary>
        /// <typeparam name="T">数据库查询的List T类型</typeparam>
        /// <typeparam name="TModel">WCF返回的实体List TModel类型</typeparam>
        /// <param name="tList">数据库查询的List T</param>
        /// <returns></returns>
        public static List<TModel> ParseDomainListToModelList<T, TModel>(this List<T> tList)
            where T : class, new()
            where TModel : class, new()
        {
            if (tList == null || tList.Count == 0)
                return null;
            var tType = tList[0].GetType();
            var properties = tType.GetProperties();

            var tModelList = new List<TModel>();


            foreach (var t in tList)
            {
                var tModel = new TModel();
                var tModelType = tModel.GetType();
                foreach (var property in properties)
                {
                    object value = property.GetValue(t, null);
                    var destProperty = tModelType.GetProperty(property.Name);
                    if (destProperty != null)
                        destProperty.SetValue(tModel, value, null);
                }
                tModelList.Add(tModel);
            }
            return tModelList;
        }
    }
}
